package com.survey.demo.ui.fragment;

import android.annotation.SuppressLint;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.android.material.tabs.TabLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.base.BaseAdapter;
import com.hjq.widget.layout.WrapRecyclerView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.survey.demo.R;
import com.survey.demo.aop.SingleClick;
import com.survey.demo.app.TitleBarFragment;
import com.survey.demo.http.bean.CommonTestDataEntity;
import com.survey.demo.http.bean.HomeEntity;
import com.survey.demo.ui.activity.HomeActivity;
import com.survey.demo.ui.activity.InsertAddrActivity;
import com.survey.demo.ui.activity.SearchActivity;
import com.survey.demo.ui.adapter.HomeShopAdapter;
import com.survey.demo.ui.adapter.HomeShopingBannerAdapter;
import com.survey.demo.ui.adapter.StatusAdapter;
import com.survey.demo.widget.MyViewPagerIndicator;
import com.survey.demo.widget.SpaceItemDecoration;
import com.survey.demo.widget.VerticalTextView;
import com.survey.demo.widget.XCollapsingToolbarLayout;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.util.BannerUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 *    author : Android 轮子哥
 *    github : https://github.com/getActivity/AndroidProject
 *    time   : 2018/10/18
 *    desc   : 首页 Fragment
 */
public final class HomeFragment extends TitleBarFragment<HomeActivity>
        implements XCollapsingToolbarLayout.OnScrimsListener, OnRefreshLoadMoreListener,
        BaseAdapter.OnItemClickListener  {

    @BindView(R.id.ctl_home_bar)
    XCollapsingToolbarLayout mCollapsingToolbarLayout;
    @BindView(R.id.tv_home_hint)
    TextView mHintView;
    @BindView(R.id.tb_home_title)
    Toolbar mToolbar;
    @BindView(R.id.tv_home_address)
    TextView mAddressView;
    @BindView(R.id.iv_home_message)
    AppCompatImageView mSearchView;
    @BindView(R.id.verticalTv)
    VerticalTextView verticalTv;
    @BindView(R.id.tl_home_tab)
    TabLayout mTabLayout;
    @BindView(R.id.kind_recy)
    RecyclerView kindRecy;
    @BindView(R.id.rl_status_refresh)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.rv_status_list)
    WrapRecyclerView mRecyclerView;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.indicator_line)
    MyViewPagerIndicator indicator;
    private HomeShopingBannerAdapter homeShopingBannerAdapter;
    private HomeShopAdapter mAdapter;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_fragment;
    }

    @Override
    protected void initView() {
        String[] kinds = getResources().getStringArray(R.array.home_kind);
        homeShopingBannerAdapter = new HomeShopingBannerAdapter(CommonTestDataEntity.getTestData());
        banner.setAdapter(homeShopingBannerAdapter)//设置适配器
                .addBannerLifecycleObserver(this)//添加生命周期观察者
                .setOnBannerListener((data, position) -> {
                    //Snackbar.make(banner, ((CommonTestDataEntity) data).title, Snackbar.LENGTH_SHORT).show();
                });
        banner.setIndicator(new CircleIndicator(getActivity()), false); //false  时候,不显示指示器
        banner.setIndicatorSelectedWidth((int) BannerUtils.dp2px(10));
//        //设置指示器
        indicator.setViewPager(banner.getViewPager2(),CommonTestDataEntity.getTestData().size(), true);
        mAdapter = new HomeShopAdapter(getAttachActivity());
        mAdapter.setOnItemClickListener(this);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),2));
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(2, 38, true));
        mRecyclerView.setAdapter(mAdapter);
        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        kindRecy.setLayoutManager(new GridLayoutManager(getActivity(),4));
        BaseQuickAdapter adapter =new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_home_top, Arrays.asList(kinds)) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, String bean) {
                baseViewHolder.setText(R.id.tv_menu_title_home,bean);
                ImageView iv = (ImageView)baseViewHolder.findView(R.id.iv_menu_home);
                iv.setImageResource(getResources().obtainTypedArray(R.array.home_icon_values).getResourceId(baseViewHolder.getPosition(), 0));
            }
        };
        kindRecy.setAdapter(adapter);
        // 给这个 ToolBar 设置顶部内边距，才能和 TitleBar 进行对齐
        ImmersionBar.setTitleBar(getAttachActivity(), mToolbar);
        initVText();
        initTab();
        //设置渐变监听
        mCollapsingToolbarLayout.setOnScrimsListener(this);
        setOnClickListener(R.id.tv_home_hint);
    }

    private void initTab() {
        //添加标题
        mTabLayout.addTab(mTabLayout.newTab().setText("全部"),0,true);
        mTabLayout.addTab(mTabLayout.newTab().setText("电光产品"),1,false);
        mTabLayout.addTab(mTabLayout.newTab().setText("无人机"),2,false);
        mTabLayout.addTab(mTabLayout.newTab().setText("激光产品"),3,false);
        mTabLayout.addTab(mTabLayout.newTab().setText("移动设备"),4,false);
        mTabLayout.addTab(mTabLayout.newTab().setText("移动设备"),5,false);

        //设置tab栏属性
        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mTabLayout.setTabRippleColor(ColorStateList.valueOf(Color.parseColor("#00000000")));
        for (int i = 0; i < mTabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(getTabView(tab.getText().toString()));
            }
            if(i==0){
                View view = tab.getCustomView();
                if (null != view && view instanceof TextView) {
                    ((TextView) view).setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    ((TextView) view).setText(tab.getText());
                    ((TextView) view).setTextColor(Color.parseColor("#232323"));
                    ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                }
            }
        }
        //底部导航栏切换监听
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                View view = tab.getCustomView();
                if (null != view && view instanceof TextView) {
                    ((TextView) view).setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    ((TextView) view).setText(tab.getText());
                    ((TextView) view).setTextColor(Color.parseColor("#232323"));
                    ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                View view = tab.getCustomView();
                if (null != view && view instanceof TextView) {
                    ((TextView) view).setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    ((TextView) view).setText(tab.getText());
                    ((TextView) view).setTextColor(Color.parseColor("#707070"));
                    ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private View getTabView(String  text) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.tab_item, null);
        TextView textView = (TextView) view.findViewById(R.id.tab_item_textview);
        textView.setText(text);
        return view;
    }

    private void initVText() {
        ArrayList<String> data = new ArrayList<String>();
        data.add("2020.1.11");
        data.add("2020.1.12");
        data.add("2020.1.13");
        data.add("2020.1.14");
//        if (touTiaoListBean != null) {
//            for (int i = 0; i < touTiaoListBean.data.size(); i++) {
//                data.add(touTiaoListBean.data.get(i).title);
//            }
//        }
        verticalTv.setTextList(data);
        verticalTv.setText(14, 10, ContextCompat.getColor(requireActivity(), R.color.black33));
        verticalTv.setTextStillTime(4000);
        verticalTv.setAnimTime(200);
        verticalTv.startAutoScroll();
        verticalTv.setOnItemClickListener(new VerticalTextView.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //跳转到头条详情
                //startActivity(new Intent(context, MessageDetailActivity.class).putExtra("id", touTiaoListBean.data.get(position).id + ""));
            }
        });
    }
    @Override
    protected void initData() {
        mAdapter.setData(analogData());
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_home_hint:
                 startActivity(SearchActivity.class);
                break;
        }
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    @Override
    public boolean isStatusBarDarkFont() {
        return mCollapsingToolbarLayout.isScrimsShown();
    }

    /**
     * CollapsingToolbarLayout 渐变回调
     *
     * {@link XCollapsingToolbarLayout.OnScrimsListener}
     */
    @SuppressLint("RestrictedApi")
    @Override
    public void onScrimsStateChange(XCollapsingToolbarLayout layout, boolean shown) {
        if (shown) {
            mAddressView.setTextColor(ContextCompat.getColor(getAttachActivity(), R.color.black));
            mHintView.setBackgroundResource(R.drawable.home_search_bar_gray_bg);
            Drawable drawable= getResources().getDrawable(R.mipmap.search_top);
            /// 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mHintView.setCompoundDrawables(drawable,null,null,null);
            mHintView.setTextColor(ContextCompat.getColor(getAttachActivity(), R.color.black60));
            mSearchView.setSupportImageTintList(ColorStateList.valueOf(getColor(R.color.common_icon_color)));
            getStatusBarConfig().statusBarDarkFont(true).init();
        } else {
            Drawable drawable= getResources().getDrawable(R.mipmap.search_icon);
            /// 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mAddressView.setTextColor(ContextCompat.getColor(getAttachActivity(), R.color.white));
            mHintView.setBackgroundResource(R.drawable.home_search_bar_transparent_bg);
            mHintView.setCompoundDrawables(drawable,null,null,null);
            mHintView.setTextColor(ContextCompat.getColor(getAttachActivity(), R.color.white60));
            mSearchView.setSupportImageTintList(ColorStateList.valueOf(getColor(R.color.white)));
            getStatusBarConfig().statusBarDarkFont(false).init();
        }
    }
    /**
     * {@link BaseAdapter.OnItemClickListener}
     *
     * @param recyclerView      RecyclerView对象
     * @param itemView          被点击的条目对象
     * @param position          被点击的条目位置
     */
    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        toast(mAdapter.getItem(position).getTitle());
    }
    /**
     * 模拟数据
     */
    private List<HomeEntity> analogData() {
        List<HomeEntity> data = new ArrayList<HomeEntity>();
        for (int i = mAdapter.getItemCount(); i < mAdapter.getItemCount() + 20; i++) {
            HomeEntity entity=new HomeEntity();
            entity.setImg("");
            entity.setTitle("请输入你的商品标题");
            entity.setPrice("358");
            if(i%3==0){
                entity.setUse(true);
            }else {
                entity.setUse(false);
            }
            data.add(entity);
        }
        return data;
    }
    /**
     * {@link OnRefreshLoadMoreListener}
     */

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        postDelayed(() -> {
            mAdapter.clearData();
            mAdapter.setData(analogData());
            mRefreshLayout.finishRefresh();
        }, 1000);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        postDelayed(() -> {
            mAdapter.addData(analogData());
            mRefreshLayout.finishLoadMore();

            mAdapter.setLastPage(mAdapter.getItemCount() >= 100);
            mRefreshLayout.setNoMoreData(mAdapter.isLastPage());
        }, 1000);
    }
}